package com.kongjs.application.controller.rest;

import com.kongjs.application.model.entity.Posts;
import com.kongjs.application.service.IPostsService;
import com.kongjs.common.rest.annotation.Rest;
import jakarta.annotation.Resource;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@Rest
@RestController
@RequestMapping("/articles")
public class ArticleController {

    @Resource
    private IPostsService postsService;

    @PatchMapping("/{id}")
    public void action(@PathVariable Long id, @RequestParam String action) {
        Optional<Posts> optionalPosts = postsService.getOptById(id);
        if (optionalPosts.isPresent()) {
            Posts post = optionalPosts.get();
            if (action.equals("like")) {
                if (ObjectUtils.isEmpty(post.getPostLikes())) {
                    post.setPostLikes(0L);
                }
                post.setPostLikes(post.getPostLikes() + 1);
                postsService.updateById(post);
            } else if (action.equals("dislike")) {
                if (ObjectUtils.isEmpty(post.getPostDislikes())) {
                    post.setPostDislikes(0L);
                }
                post.setPostDislikes(post.getPostDislikes() + 1);
                postsService.updateById(post);
            }
        }
    }
}
